//
//  AppDelegate.m
//  SunXi
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 大远. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()<IChatManagerDelegate,WeiboSDKDelegate,WXApiDelegate,TencentSessionDelegate>
@property (nonatomic, strong)CoreDataManager *manager;
@end

@implementation AppDelegate{
    NSTimer *_backstage;
    UIImageView *_imageView;
    RESideMenu *_sideMenuVC;
    TencentOAuth *_tencentOAuth;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    HomeViewController *homeVC = [[HomeViewController alloc]init];
    UINavigationController *homeNaVC  = [[UINavigationController alloc]initWithRootViewController:homeVC];
    RECViewController *leftVC = [[RECViewController alloc]init];
    RightViewController *rightVC = [[RightViewController alloc]init];
    /**
     *  设置抽屉
     */
    _sideMenuVC = [[RESideMenu alloc]initWithContentViewController:homeNaVC leftMenuViewController:leftVC rightMenuViewController:rightVC];
    _sideMenuVC.menuPreferredStatusBarStyle = UIStatusBarStyleLightContent;
    _sideMenuVC.contentViewShadowOffset = CGSizeMake(0, 0);
    _sideMenuVC.contentViewShadowColor = [UIColor blackColor];
    _sideMenuVC.contentViewShadowOpacity = 0.6;
    _sideMenuVC.contentViewShadowRadius = 12;
    _sideMenuVC.backgroundImage = [UIImage imageNamed:@"drawBackPic.jpg"];
    /**
     *  设置欢迎界面
     */
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

    BOOL first = [ud boolForKey:@"firstcome"];
    if (!first) {
        first = YES;
        [ud setBool:first forKey:@"firstcome"];
        WelcomeViewController *weVC = [[WelcomeViewController alloc]init];
        NSArray *imagearr = @[@"FriendPic02.jpg"];
        
        [weVC showGuidePage:imagearr];
        self.window.rootViewController = weVC;
        void(^block)()= ^(){
            _sideMenuVC.view.alpha = 0;
            self.window.rootViewController = _sideMenuVC;
            [UIView animateWithDuration:1 animations:^{
                _sideMenuVC.view.alpha = 1;
            }];
        };
        weVC.block = block;
        
    }else{
    
        self.window.rootViewController = _sideMenuVC;
    }
    /**
     *  后台权限
     */
    NSError* error;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    _imageView = [[UIImageView alloc]init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createData) name:@"更换音乐" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createData) name:@"开始音乐" object:nil];
    /**
     *  集成环信 上线推广市修改证书名
     */
#warning 修改证书名;
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"heidayuan#sunxi" apnsCertName:@"sunxiceshi"];
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    /**
     *  设置coreData管理者
     */
    self.manager = [CoreDataManager defaults];
    /**
     *  继承微博分享
     */
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:WBAPPID];
    
    [WXApi registerApp:@"wxaca5ac093f774436"];
    /**
     *  设置QQ
     */
    _tencentOAuth = [[TencentOAuth alloc]initWithAppId:@"1104924213" andDelegate:self];
    /**
     *  远程推送
     */
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0f) {
   
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
        
    } else {
        //系统iOS8.0以下使用
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    
//    [XGPush startApp:2200169716 appKey:@"ILXVB58D531R"];
    [APService setupWithOption:launchOptions];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    
    
    
    return YES;
}
//注册失败返回ERROR
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error ===== %@",error);
}
//5.发送同时成功返回通知内容
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    NSLog(@"userInfo ===== %@",userInfo);
    [APService handleRemoteNotification:userInfo];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

//2.注册成功后APNS返回Token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    //3.将获取的Token发送给自己的服务器
//    [XGPush registerDevice:deviceToken];
    [APService registerDeviceToken:deviceToken];
    
    NSLog(@"Token ===== %@",[deviceToken description]);
    
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    if (userInfo) {
        if (userInfo[@"web"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"网页推送" object:userInfo];
        }
    }
    
    
}


/**
 *  自动登陆完成回调
 */
- (void)didAutoLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error{
    if (!error) {
    [UserModel shareSingleton].userName = loginInfo[@"username"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"自动登录" object:nil];
    }
}
/**
 *  收到好友添加请求是回调
 */
- (void)didReceiveBuddyRequest:(NSString *)username
                       message:(NSString *)message{
    usermessModel * model = [[usermessModel alloc]init];
    model.name = username;
    model.mess = message;
    [[UserModel shareSingleton].waitFriend addObject:model];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"收到添加" object:nil];
}
/**
 *  收到在线消息
 */
- (void)didReceiveMessage:(EMMessage *)message{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserMess" inManagedObjectContext:self.manager.managedObjectContext];
    UserMess *model = [[UserMess alloc]initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
//赋值
    model.type = @1;
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    model.mess = ((EMTextMessageBody *)msgBody).text;
    model.user = message.from;
    model.time = [NSNumber numberWithLongLong:message.timestamp];
    model.look = @1;
    [self.manager saveContext];
     NSLog(@"url ===== %@",[self.manager applicationDocumentsDirectory]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"新消息" object:nil];
}
- (void)createData{
      [_imageView sd_setImageWithURL:[NSURL URLWithString:[[[RadioSavemodel shareSingleton].playlistArr objectAtIndex:[RadioSavemodel shareSingleton].playNumber]  coverimg]] placeholderImage:[UIImage imageNamed:@"zan"]];

}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
//    NSLog(@"\n\n倔强的打出一行字告诉你我要挂起了。。\n\n");
    
    //有音乐播放时，才给后台权限，不做流氓应用。
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    _backstage = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(configNowPlayingInfoCenter) userInfo:nil repeats:YES];

}
-(void)configNowPlayingInfoCenter{
    
    
    @autoreleasepool {
        
         if ([myplay sharePlayer].rate > 0  && [[[RadioSavemodel shareSingleton].playlistArr objectAtIndex:[RadioSavemodel shareSingleton].playNumber]  title].length > 0) {
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        
        [dict setObject:[[[RadioSavemodel shareSingleton].playlistArr objectAtIndex:[RadioSavemodel shareSingleton].playNumber]  title]forKey:MPMediaItemPropertyTitle];
//

        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:_imageView.image];
        [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
       
             
             //剩余时间
        [dict setObject:[NSNumber numberWithFloat:(CMTimeGetSeconds([myplay sharePlayer].currentItem.duration))] forKey:MPMediaItemPropertyPlaybackDuration];
        
        [dict setObject:[NSNumber numberWithFloat:CMTimeGetSeconds([myplay sharePlayer].currentItem.currentTime)] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
        
        

            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    }
    
    }
    
    
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlPause:
                //点击了暂停
                [[myplay sharePlayer] pause]; ;
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                //点击了下一首
//                self.plVC = [PlayerController new];
//                [self.plVC BAcklookNext];
//                [_plVC release];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                //点击了上一首
//                self.plVC = [PlayerController new];
//                [self.plVC upmusicclick];
                //此时需要更改歌曲信息
                break;
            case UIEventSubtypeRemoteControlPlay:
                [[myplay sharePlayer] play];
                break;
            default:
                break;
                
        }
    }
}
//APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];

}
//APP将要从后台回来
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    [[EaseMob sharedInstance] applicationWillEnterForeground:application];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [_backstage invalidate];

    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
//申请处理时间
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
     [[EaseMob sharedInstance] applicationWillTerminate:application];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [WXApi handleOpenURL:url delegate:self];
    [TencentOAuth HandleOpenURL:url];

    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [TencentOAuth HandleOpenURL:url];
    [WXApi handleOpenURL:url delegate:self];
    return [WeiboSDK handleOpenURL:url delegate:self ];
}





- (void)didReceiveWeiboRequest:(WBBaseRequest *)request{
    [[ShareWindow sharedInstance] hidd];
     
    //回调方法
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    [[ShareWindow sharedInstance] hidd];
    
    //回调方法
}

/**
 *  微信回调
 */
- (void)onReq:(BaseReq *)req{
    [[ShareWindow sharedInstance] hidd];

}
- (void)onResp:(BaseResp *)resp{
    [[ShareWindow sharedInstance] hidd];

}
//QQ回调

- (void)tencentDidLogin{
    
}
- (void)tencentDidLogout{
    
}
- (void)tencentDidNotNetWork{
    
}
@end
